﻿using ImportPlcPointPosition.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace ImportPlcPointPosition
{
    /// <summary>
    /// 读取配置文件
    /// </summary>
    public class AppConfig
    {

        /// <summary>
        /// 配置构造器
        /// </summary>
        static IConfigurationRoot ConfigBuild;

        /// <summary>
        /// 锁
        /// </summary>
        static readonly object _lock = new object();

        public static OptionsSetting AppsettingConfig { get; internal set; }

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">对应的键</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            if (ConfigBuild == null)
            {
                lock (_lock)
                {
                    if (ConfigBuild == null)
                    {
                        var builder = new ConfigurationBuilder();
                        builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                        ConfigBuild = builder.Build();
                    }
                }
            }
            //需要安装两个nuget
            //Microsoft.Extensions.Configuration.Json
            //Microsoft.Extensions.Configuration.Binder
            return ConfigBuild.GetValue<T>(key);
        }


        public static T GetConfig<T>() where T : class,new() 
        {
            if (ConfigBuild == null)
            {
                lock (_lock)
                {
                    if (ConfigBuild == null)
                    {
                        var builder = new ConfigurationBuilder();
                        builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                        ConfigBuild = builder.Build();
                    }
                }
            }
            //需要安装两个nuget
            //Microsoft.Extensions.Configuration.Json
            //Microsoft.Extensions.Configuration.Binder
            T config = new T();
            ConfigBuild.Bind(config);
            return config;
        }


    }
}
